#!/usr/bin/env python3
"""
Ford Focus车型页面逆向分析脚本
分析 url0: https://www.ford.co.uk/cars/focus#models
寻找车款信息和"See Full Specification"内容
"""

import sys
import os
import json
import time
from datetime import datetime

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from src.base import BaseWebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException

class FocusPageAnalyzer:
    """Ford Focus页面分析器"""
    
    def __init__(self):
        self.driver_manager = BaseWebDriver()
        self.driver = None
        self.wait = None
        self.results = {
            "analysis_date": datetime.now().isoformat(),
            "target_url": "",
            "page_status": "",
            "models_found": [],
            "specifications_info": {},
            "api_calls_detected": [],
            "errors": []
        }
    
    def setup_driver(self):
        """初始化WebDriver"""
        try:
            print("🚀 初始化WebDriver...")
            self.driver_manager.setup_driver()
            self.driver = self.driver_manager.driver
            self.wait = WebDriverWait(self.driver, 10)
            print("✅ WebDriver初始化成功")
            return True
        except Exception as e:
            error_msg = f"WebDriver初始化失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return False
    
    def load_config(self):
        """加载配置文件"""
        try:
            with open('fetchNgc2.json', 'r', encoding='utf-8') as f:
                config = json.load(f)
            url0 = config.get('sub_model', {}).get('url0', '')
            if not url0:
                raise ValueError("url0未找到")
            return url0
        except Exception as e:
            error_msg = f"加载配置失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return None
    
    def navigate_to_page(self, url):
        """导航到目标页面"""
        try:
            print(f"🌐 正在访问: {url}")
            self.results["target_url"] = url
            
            self.driver.get(url)
            
            # 等待页面加载
            print("⏳ 等待页面加载...")
            time.sleep(5)
            
            # 检查页面状态
            current_url = self.driver.current_url
            title = self.driver.title
            
            print(f"📍 当前URL: {current_url}")
            print(f"📄 页面标题: {title}")
            
            if "404" in title or "not found" in title.lower():
                self.results["page_status"] = "404 - Page Not Found"
                return False
            else:
                self.results["page_status"] = "Success"
                return True
                
        except Exception as e:
            error_msg = f"页面导航失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return False
    
    def handle_cookies(self):
        """处理Cookie弹窗"""
        try:
            print("🍪 处理Cookie弹窗...")
            
            # 常见的Cookie同意按钮选择器
            cookie_selectors = [
                "button[id*='accept']",
                "button[class*='accept']",
                "button[data-testid*='accept']",
                "#onetrust-accept-btn-handler",
                ".ot-sdk-show-settings",
                "[aria-label*='Accept']",
                "[title*='Accept']"
            ]
            
            for selector in cookie_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    if elements:
                        element = elements[0]
                        if element.is_displayed():
                            self.driver.execute_script("arguments[0].click();", element)
                            print(f"✅ 点击了Cookie按钮: {selector}")
                            time.sleep(2)
                            break
                except:
                    continue
                    
        except Exception as e:
            print(f"⚠️ Cookie处理异常: {e}")
    
    def analyze_models(self):
        """分析页面中的车型信息"""
        try:
            print("\n🚗 分析车型信息...")
            
            # 寻找车型相关的元素
            model_selectors = [
                # 通用车型选择器
                "[data-cy*='model']",
                "[class*='model']",
                "[class*='variant']",
                "[class*='trim']",
                "div[class*='card']",
                "div[class*='tile']",
                ".model-card",
                ".variant-card",
                ".trim-level",
                
                # Focus特定选择器
                "[data-testid*='focus']",
                "[class*='focus']",
                
                # 价格和规格选择器
                "[class*='price']",
                "[class*='spec']",
                "button[class*='specification']",
                "a[href*='specification']",
                "button:contains('See Full Specification')",
                "a:contains('Full Specification')"
            ]
            
            models_found = []
            
            for selector in model_selectors:
                try:
                    if 'contains(' in selector:
                        # 使用XPath处理contains
                        xpath = f"//*[contains(text(), 'See Full Specification') or contains(text(), 'Full Specification')]"
                        elements = self.driver.find_elements(By.XPATH, xpath)
                    else:
                        elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    
                    if elements:
                        print(f"  📋 选择器 '{selector}' 找到 {len(elements)} 个元素")
                        
                        for i, element in enumerate(elements[:5]):  # 只检查前5个
                            try:
                                text = element.text.strip()
                                tag_name = element.tag_name
                                class_name = element.get_attribute('class') or ''
                                data_cy = element.get_attribute('data-cy') or ''
                                
                                if text and len(text) > 0:
                                    model_info = {
                                        "selector": selector,
                                        "index": i,
                                        "tag": tag_name,
                                        "text": text[:200],  # 限制文本长度
                                        "class": class_name[:100],
                                        "data_cy": data_cy,
                                        "is_displayed": element.is_displayed()
                                    }
                                    models_found.append(model_info)
                                    
                            except Exception as e:
                                print(f"    ❌ 元素分析失败: {e}")
                                
                except Exception as e:
                    print(f"  ❌ 选择器 '{selector}' 失败: {e}")
                    continue
            
            self.results["models_found"] = models_found
            print(f"✅ 共找到 {len(models_found)} 个潜在车型元素")
            
            return len(models_found) > 0
            
        except Exception as e:
            error_msg = f"车型分析失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return False
    
    def analyze_specifications(self):
        """分析"See Full Specification"相关内容"""
        try:
            print("\n📋 分析规格说明内容...")
            
            # 寻找规格相关的按钮和链接
            spec_selectors = [
                "button:contains('See Full Specification')",
                "a:contains('See Full Specification')",
                "button:contains('Full Specification')",
                "a:contains('Full Specification')",
                "button:contains('Specification')",
                "a:contains('Specification')",
                "[data-testid*='specification']",
                "[class*='specification']",
                "[href*='specification']",
                "[onclick*='specification']"
            ]
            
            specifications_found = []
            
            for selector in spec_selectors:
                try:
                    if 'contains(' in selector:
                        # 转换为XPath
                        text_to_find = selector.split("'")[1]
                        xpath = f"//*[contains(text(), '{text_to_find}')]"
                        elements = self.driver.find_elements(By.XPATH, xpath)
                    else:
                        elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    
                    if elements:
                        print(f"  🔍 规格选择器 '{selector}' 找到 {len(elements)} 个元素")
                        
                        for i, element in enumerate(elements[:3]):
                            try:
                                spec_info = {
                                    "selector": selector,
                                    "index": i,
                                    "tag": element.tag_name,
                                    "text": element.text.strip()[:100],
                                    "href": element.get_attribute('href'),
                                    "onclick": element.get_attribute('onclick'),
                                    "class": element.get_attribute('class'),
                                    "is_displayed": element.is_displayed(),
                                    "is_clickable": element.is_enabled()
                                }
                                specifications_found.append(spec_info)
                                
                            except Exception as e:
                                print(f"    ❌ 规格元素分析失败: {e}")
                
                except Exception as e:
                    print(f"  ❌ 规格选择器 '{selector}' 失败: {e}")
                    continue
            
            self.results["specifications_info"] = {
                "elements_found": specifications_found,
                "total_count": len(specifications_found)
            }
            
            print(f"✅ 共找到 {len(specifications_found)} 个规格相关元素")
            
            return len(specifications_found) > 0
            
        except Exception as e:
            error_msg = f"规格分析失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return False
    
    def monitor_network_requests(self):
        """监控网络请求（简化版）"""
        try:
            print("\n🔍 检查页面中的API调用...")
            
            # 查找页面中的脚本和请求
            scripts = self.driver.find_elements(By.TAG_NAME, "script")
            
            api_patterns = [
                "servicescache.ford.com",
                "/api/",
                "focus",
                "model",
                "specification",
                "vehicle"
            ]
            
            api_calls = []
            
            for script in scripts[:10]:  # 只检查前10个脚本
                try:
                    script_content = script.get_attribute('innerHTML') or script.get_attribute('src') or ''
                    
                    for pattern in api_patterns:
                        if pattern in script_content.lower():
                            api_calls.append({
                                "pattern": pattern,
                                "found_in": "script",
                                "content_snippet": script_content[:200]
                            })
                            
                except Exception as e:
                    continue
            
            self.results["api_calls_detected"] = api_calls
            print(f"✅ 检测到 {len(api_calls)} 个潜在API调用")
            
        except Exception as e:
            error_msg = f"网络监控失败: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
    
    def save_results(self):
        """保存分析结果"""
        try:
            output_file = "./release/focus_page_analysis.json"
            os.makedirs(os.path.dirname(output_file), exist_ok=True)
            
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(self.results, f, ensure_ascii=False, indent=2)
            
            print(f"💾 分析结果已保存到: {output_file}")
            
        except Exception as e:
            print(f"❌ 保存结果失败: {e}")
    
    def cleanup(self):
        """清理资源"""
        try:
            if self.driver:
                self.driver_manager.cleanup()
                print("🧹 WebDriver已清理")
        except Exception as e:
            print(f"⚠️ 清理资源时出错: {e}")
    
    def run_analysis(self):
        """运行完整分析"""
        try:
            print("🔍 开始Ford Focus页面逆向分析...")
            print("=" * 50)
            
            # 1. 加载配置
            url0 = self.load_config()
            if not url0:
                return False
            
            # 2. 初始化WebDriver
            if not self.setup_driver():
                return False
            
            # 3. 导航到页面
            if not self.navigate_to_page(url0):
                return False
            
            # 4. 处理Cookie
            self.handle_cookies()
            
            # 5. 分析车型
            self.analyze_models()
            
            # 6. 分析规格说明
            self.analyze_specifications()
            
            # 7. 监控网络请求
            self.monitor_network_requests()
            
            # 8. 保存结果
            self.save_results()
            
            print("\n🎉 分析完成！")
            return True
            
        except Exception as e:
            error_msg = f"分析过程出错: {e}"
            print(f"❌ {error_msg}")
            self.results["errors"].append(error_msg)
            return False
        
        finally:
            self.cleanup()

def main():
    """主函数"""
    analyzer = FocusPageAnalyzer()
    success = analyzer.run_analysis()
    
    if success:
        print("\n📊 分析结果摘要:")
        print(f"  🎯 目标URL: {analyzer.results['target_url']}")
        print(f"  📄 页面状态: {analyzer.results['page_status']}")
        print(f"  🚗 找到车型元素: {len(analyzer.results['models_found'])} 个")
        print(f"  📋 找到规格元素: {analyzer.results['specifications_info'].get('total_count', 0)} 个")
        print(f"  🔍 检测到API调用: {len(analyzer.results['api_calls_detected'])} 个")
        print(f"  ❌ 错误数量: {len(analyzer.results['errors'])}")
        
        if analyzer.results['errors']:
            print("\n⚠️ 错误详情:")
            for error in analyzer.results['errors']:
                print(f"    - {error}")
    else:
        print("❌ 分析失败")

if __name__ == "__main__":
    main()
